<?php
declare(strict_types=1);

namespace app\common\model;

use think\Model;

class AdminRole extends Model
{
    protected $pk = 'id';
    protected $name = 'admin_role';
    
    // 关闭自动时间戳
    protected $autoWriteTimestamp = false;
    
    /**
     * 定义与管理员的关联
     */
    public function admin()
    {
        return $this->belongsTo(Admin::class, 'admin_id', 'admin_id');
    }
    
    /**
     * 定义与角色的关联
     */
    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id', 'role_id')
            ->where('status', 1)
            ->whereNull('delete_time');
    }
    
    /**
     * 批量保存管理员角色关联
     * @param int $adminId
     * @param array $roleIds
     * @return bool
     */
    public function saveAdminRoles(int $adminId, array $roleIds): bool
    {
        // 先删除原有关联
        $this->where('admin_id', $adminId)->delete();
        
        if (empty($roleIds)) {
            return true;
        }
        
        // 添加新的关联
        $data = [];
        foreach ($roleIds as $roleId) {
            $data[] = [
                'admin_id' => $adminId,
                'role_id' => $roleId
            ];
        }
        
        return $this->insertAll($data) > 0;
    }
} 